package com.deliveryservicesystem.service.crud.impl;

import com.deliveryservicesystem.app.exceptions.NonexistentEntityException;
import com.deliveryservicesystem.app.exceptions.PreexistingEntityException;
import com.deliveryservicesystem.dataaccess.PersistenceDbManager;
import com.deliveryservicesystem.model.Billing;
import com.deliveryservicesystem.model.Subscription;
import com.deliveryservicesystem.service.crud.BillingCrudService;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 * File Name: BillingCrudServiceImpl.java
 * Version:
 * Description:
 * Package: com.deliveryservicesystem.service.crud.impl
 * Author: Lance
 * Date: Jun 20, 2012
 * Editor:
 */
public class BillingCrudServiceImpl implements BillingCrudService
{

    private static final long serialVersionUID = 1L;
    private EntityManagerFactory emf = null;

    /**
     * Create the new CRUD service. Internally setting the EntityManagerFactory
     * using database details from database properties
     */
    public BillingCrudServiceImpl()
    {
        PersistenceDbManager persistenceManager = PersistenceDbManager.getInstance();
        this.emf = persistenceManager.getEntityManagerFactory();
    }

    @Override
    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    @Override
    public void create(Billing billing) throws PreexistingEntityException, Exception
    {
        if (billing.getSubscriptionList() == null)
        {
            billing.setSubscriptionList(new ArrayList<Subscription>());
        }
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Subscription> attachedSubscriptionList = new ArrayList<>();
            for (Subscription subscriptionListSubscriptionToAttach : billing.getSubscriptionList())
            {
                subscriptionListSubscriptionToAttach = em.getReference(subscriptionListSubscriptionToAttach.getClass(), subscriptionListSubscriptionToAttach.getSubscriptionNo());
                attachedSubscriptionList.add(subscriptionListSubscriptionToAttach);
            }
            billing.setSubscriptionList(attachedSubscriptionList);
            em.persist(billing);
            for (Subscription subscriptionListSubscription : billing.getSubscriptionList())
            {
                Billing oldBillingNoOfSubscriptionListSubscription = subscriptionListSubscription.getBillingNo();
                subscriptionListSubscription.setBillingNo(billing);
                subscriptionListSubscription = em.merge(subscriptionListSubscription);
                if (oldBillingNoOfSubscriptionListSubscription != null)
                {
                    oldBillingNoOfSubscriptionListSubscription.getSubscriptionList().remove(subscriptionListSubscription);
                    oldBillingNoOfSubscriptionListSubscription = em.merge(oldBillingNoOfSubscriptionListSubscription);
                }
            }
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            if (findById(billing.getBillingNo()) != null)
            {
                throw new PreexistingEntityException("Billing " + billing + " already exists.", ex);
            }
            throw ex;
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public void edit(Billing billing) throws NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Billing persistentBilling = em.find(Billing.class, billing.getBillingNo());
            List<Subscription> subscriptionListOld = persistentBilling.getSubscriptionList();
            List<Subscription> subscriptionListNew = billing.getSubscriptionList();
            List<Subscription> attachedSubscriptionListNew = new ArrayList<>();
            for (Subscription subscriptionListNewSubscriptionToAttach : subscriptionListNew)
            {
                subscriptionListNewSubscriptionToAttach = em.getReference(subscriptionListNewSubscriptionToAttach.getClass(), subscriptionListNewSubscriptionToAttach.getSubscriptionNo());
                attachedSubscriptionListNew.add(subscriptionListNewSubscriptionToAttach);
            }
            subscriptionListNew = attachedSubscriptionListNew;
            billing.setSubscriptionList(subscriptionListNew);
            billing = em.merge(billing);
            for (Subscription subscriptionListOldSubscription : subscriptionListOld)
            {
                if (!subscriptionListNew.contains(subscriptionListOldSubscription))
                {
                    subscriptionListOldSubscription.setBillingNo(null);
                    subscriptionListOldSubscription = em.merge(subscriptionListOldSubscription);
                }
            }
            for (Subscription subscriptionListNewSubscription : subscriptionListNew)
            {
                if (!subscriptionListOld.contains(subscriptionListNewSubscription))
                {
                    Billing oldBillingNoOfSubscriptionListNewSubscription = subscriptionListNewSubscription.getBillingNo();
                    subscriptionListNewSubscription.setBillingNo(billing);
                    subscriptionListNewSubscription = em.merge(subscriptionListNewSubscription);
                    if (oldBillingNoOfSubscriptionListNewSubscription != null && !oldBillingNoOfSubscriptionListNewSubscription.equals(billing))
                    {
                        oldBillingNoOfSubscriptionListNewSubscription.getSubscriptionList().remove(subscriptionListNewSubscription);
                        oldBillingNoOfSubscriptionListNewSubscription = em.merge(oldBillingNoOfSubscriptionListNewSubscription);
                    }
                }
            }
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = billing.getBillingNo();
                if (findById(id) == null)
                {
                    throw new NonexistentEntityException("The billing with id " + id + " no longer exists.");
                }
            }
            throw ex;
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public void destroy(Integer id) throws NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Billing billing;
            try
            {
                billing = em.getReference(Billing.class, id);
                billing.getBillingNo();
            }
            catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The billing with id " + id + " no longer exists.", enfe);
            }
            List<Subscription> subscriptionList = billing.getSubscriptionList();
            for (Subscription subscriptionListSubscription : subscriptionList)
            {
                subscriptionListSubscription.setBillingNo(null);
                subscriptionListSubscription = em.merge(subscriptionListSubscription);
            }
            em.remove(billing);
            em.getTransaction().commit();
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public List<Billing> findEntities()
    {
        return findBillingEntities(true, -1, -1);
    }

    @Override
    public List<Billing> findEntities(int maxResults, int firstResult)
    {
        return findBillingEntities(false, maxResults, firstResult);
    }

    private List<Billing> findBillingEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Billing.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        }
        finally
        {
            em.close();
        }
    }

    @Override
    public Billing findById(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Billing.class, id);
        }
        finally
        {
            em.close();
        }
    }

    @Override
    public int count()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Billing> rt = cq.from(Billing.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        }
        finally
        {
            em.close();
        }
    }
}
